package com.erp.ae.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.ae.domain.AeCurrencyDescription;
import com.ruoyi.ae.api.domain.AeStoreChildOrder;
import com.ruoyi.ae.api.domain.AeStoreOrder;
import com.ruoyi.ae.api.domain.AeStoreOrderProduct;
import com.erp.ae.mapper.*;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderProduct;
import com.ruoyi.ae.api.domain.AeStoreOrderReceiptAddress;
import com.erp.ae.domain.enums.AliExpressInterfaceEnum;
import com.erp.ae.service.IAeStoreOrderService;
import com.global.iop.domain.Protocol;
import com.ruoyi.common.core.domain.R;
import com.erp.ae.utils.AeApiUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商户订单Service业务层处理
 *
 * @author erp
 * @date 2023-03-09
 */
@RequiredArgsConstructor
@Service
public class AeStoreOrderServiceImpl implements IAeStoreOrderService {
    private final AeStoreOrderReceiptAddressMapper aeStoreOrderReceiptAddressMapper;
    private final AeStoreChildOrderMapper aeStoreChildOrderMapper;

    private final AeCurrencyDescriptionMapper aeCurrencyDescriptionMapper;
    private final AeStoreOrderProductMapper aeStoreOrderProductMapper;
    private final AeStoreOrderMapper aeStoreOrderMapper;
    @Resource
    RabbitTemplate rabbitTemplate = SpringUtils.getBean(RabbitTemplate.class);

    @Override
    public R<Object> findOrderBaseInfo(String accessToken, String orderId) {
        if (StringUtils.isNotEmpty(accessToken)) {
            JSONObject msg = JSONObject.parseObject(
                    AeApiUtils.sendRequest(
                            AliExpressInterfaceEnum.findOrderBaseInfo.getCode(),
                            "param1",
                            "{" + "\"order_id\":\"" + orderId + "\"}",
                            Protocol.TOP,
                            accessToken
                    )
            );
            return R.ok(msg);
        }
        return R.fail("店铺未授权");
    }

    @Override
    public R<Object> findOrderReceiptInfo(String accessToken, Long orderId) {
        if (StringUtils.isNotEmpty(accessToken)) {
            String msg =
                    AeApiUtils.sendRequest(
                            AliExpressInterfaceEnum.findOrderReceiptInfo.getCode(),
                            "param1",
                            "{" + "\"order_id\":\"" + orderId + "\"}",
                            Protocol.TOP,
                            accessToken
                    );
            if (!msg.contains("aliexpress_trade_redefining_findorderreceiptinfo_response")) {
                return R.fail("授权失败");
            }
            AeStoreOrderReceiptAddress address = new AeStoreOrderReceiptAddress();
            JSONObject receiptAddress = JSONObject.parseObject(msg)
                    .getJSONObject("aliexpress_trade_redefining_findorderreceiptinfo_response")
                    .getJSONObject("result");
            address.setOaid(receiptAddress.getString("oaid"));
            address.setCountry(receiptAddress.getString("country"));
            address.setZip(receiptAddress.getString("zip"));
            address.setCity(receiptAddress.getString("city"));
            address.setProvince(receiptAddress.getString("province"));
            address.setPhoneCountry(receiptAddress.getString("phone_country"));
            address.setAddress2(receiptAddress.getString("address2"));
            address.setOrderId(orderId);
            //解密收货人信息
            address = tradeSellerOrderDecrypt(address, accessToken);
            AeStoreOrderReceiptAddress aeStoreOrderReceiptAddressSel = aeStoreOrderReceiptAddressMapper.selectOne(
                    new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, address.getOrderId())
            );
            if (aeStoreOrderReceiptAddressSel != null) {
                address.setId(aeStoreOrderReceiptAddressSel.getId());
            }
            aeStoreOrderReceiptAddressMapper.insertOrUpdate(address);
            return R.ok("更新成功");

        }
        return R.fail("店铺未授权");
    }

    @Override
    public R<Object> findOrderFeeRateAndCodeInfo(String accessToken, Long orderId) {
        if (StringUtils.isNotEmpty(accessToken)) {
            String msg =
                    AeApiUtils.sendRequest(
                            AliExpressInterfaceEnum.findOrderById.getCode(),
                            "param1",
                            "{" + "\"order_id\":\"" + orderId + "\"}",
                            Protocol.TOP,
                            accessToken
                    );
            if (!msg.contains("aliexpress_trade_new_redefining_findorderbyid_response")) {
                return R.fail("授权失败");
            }
            //查看返回值
            JSONObject jsonObject = JSONObject.parseObject(msg);
            JSONObject jsonObject1 = jsonObject
                    .getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response")
                    .getJSONObject("target");
            System.out.println(jsonObject1);
            JSONArray jsonArray = jsonObject1
                    .getJSONObject("child_order_list")
                    .getJSONArray("aeop_tp_child_order_dto");

            Map<String, Object> returnMap = new HashMap<>();
//            Map<String,Object> testMap = new HashMap<>();
//            testMap.put("childOrderId","test");
//            testMap.put("escrowFeeRate","test");
//            testMap.put("afflicateFeeRate","test");
//            returnMap.put("test",testMap);

            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String, Object> childOrderMap = new HashMap<>();
                JSONObject childOrder = jsonArray.getJSONObject(i);
                System.out.println(childOrder);
                String escrowFeeRate = childOrder.getString("escrow_fee_rate");
                String afflicateFeeRate = childOrder.getString("afflicate_fee_rate");

                //找到ae里面的这个子订单
                AeStoreChildOrder aeStoreChildOrder = aeStoreChildOrderMapper.selectOne(
                        new LambdaQueryWrapper<AeStoreChildOrder>().eq(AeStoreChildOrder::getChildOrderId, childOrder.getString("child_order_id"))
                );
                if (aeStoreChildOrder != null) {
                    aeStoreChildOrder.setAfflicateFeeRate(afflicateFeeRate);
                    aeStoreChildOrder.setEscrowFeeRate(escrowFeeRate);
                    aeStoreChildOrder.setEscrowFeeRate(escrowFeeRate);
                    aeStoreChildOrderMapper.insertOrUpdate(aeStoreChildOrder);
                }
                childOrderMap.put("childOrderId", aeStoreChildOrder.getChildOrderId());
                childOrderMap.put("escrowFeeRate", aeStoreChildOrder.getEscrowFeeRate());
                childOrderMap.put("afflicateFeeRate", aeStoreChildOrder.getAfflicateFeeRate());
                childOrderMap.put("productCurrencyCode", aeStoreChildOrder.getProductCurrencyCode());
                returnMap.put(aeStoreChildOrder.getChildOrderId(), childOrderMap);
            }


            return R.ok(returnMap);

        }
        return R.fail("店铺未授权");
    }

    @Override
    public R<Object> updateOrderAmount(String accessToken, Long orderId) {
        if (StringUtils.isEmpty(accessToken)) {
            JSONObject msg = JSONObject.parseObject(
                    AeApiUtils.sendRequest(
                            AliExpressInterfaceEnum.findOrderById.getCode(),
                            "param1",
                            "{" + "\"order_id\":\"" + orderId + "\"}",
                            Protocol.TOP,
                            accessToken
                    )
            );
            String newOrderAmount = msg.getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response")
                    .getJSONObject("target")
                    .getJSONObject("new_order_amount")
                    .getString("amount");
            String logisticsAmount = msg.getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response")
                    .getJSONObject("target").getJSONObject("logistics_amount").getString("amount");
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("newOrderAmount", newOrderAmount);
            returnMap.put("logisticsAmount", logisticsAmount);
            return R.ok(returnMap);
        }
        return R.fail("店铺未授权");
    }

    /**
     * 信息解密
     *
     * @param aeStoreOrderReceiptAddress
     * @param accessToken
     * @return
     */
    @Override
    public AeStoreOrderReceiptAddress tradeSellerOrderDecrypt(AeStoreOrderReceiptAddress aeStoreOrderReceiptAddress, String accessToken) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", aeStoreOrderReceiptAddress.getOrderId());
        map.put("oaid", aeStoreOrderReceiptAddress.getOaid());
        //获取卖家地址
        String returnMsg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.orderDecrypt.getCode(),
                        map,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(returnMsg);
        JSONObject addressOaInfo = JSONObject
                .parseObject(returnMsg)
                .getJSONObject("aliexpress_trade_seller_order_decrypt_response")
                .getJSONObject("result_obj");
        if (addressOaInfo != null) {
            System.out.println(addressOaInfo);
            aeStoreOrderReceiptAddress.setAddress2(addressOaInfo.getString("address2"));
            aeStoreOrderReceiptAddress.setContactPerson(addressOaInfo.getString("contact_person"));
            aeStoreOrderReceiptAddress.setDetailAddress(addressOaInfo.getString("detail_address"));
            aeStoreOrderReceiptAddress.setMobileNo(addressOaInfo.getString("mobile_no"));
            aeStoreOrderReceiptAddress.setPhoneNumber(addressOaInfo.getString("phone_number"));
            aeStoreOrderReceiptAddress.setFirstName(addressOaInfo.getString("first_name"));
            aeStoreOrderReceiptAddress.setBuyerSignerFullname(addressOaInfo.getString("buyer_signer_fullname"));
        }
        return aeStoreOrderReceiptAddress;
    }

    /**
     * @param aeStoreOrder
     * @param orderDetails
     * @param accessToken
     * @return
     * @Description: 拉取AE订单并入库
     * @Author: j.zh
     * @Date: 2024/5/10
     * @Version: 4.0.0
     **/
    @Override
    public Map<String, Object> saveAeNewOrderInfo(AeStoreOrder aeStoreOrder, JSONObject orderDetails, String accessToken) {
        //保存基本信息
        aeStoreOrder = saveAeStoreOrderByDetails(aeStoreOrder, orderDetails);

        //AE_STORE_ORDER_RECEIPT_ADDRESS 收货人信息
        JSONObject receiptAddress = orderDetails.getJSONObject("receipt_address");
        AeStoreOrderReceiptAddress aeStoreOrderReceiptAddress = new AeStoreOrderReceiptAddress();
        aeStoreOrderReceiptAddress.setAddress(receiptAddress.getString("address"));
        aeStoreOrderReceiptAddress.setAddress2(receiptAddress.getString("address2"));
        aeStoreOrderReceiptAddress.setCity(receiptAddress.getString("city"));
        aeStoreOrderReceiptAddress.setContactPerson(receiptAddress.getString("contact_person"));
        aeStoreOrderReceiptAddress.setCountry(receiptAddress.getString("country"));
        aeStoreOrderReceiptAddress.setDetailAddress(receiptAddress.getString("detail_address"));
        aeStoreOrderReceiptAddress.setMobileNo(receiptAddress.getString("mobile_no"));
        aeStoreOrderReceiptAddress.setPhoneCountry(receiptAddress.getString("phone_country"));
        aeStoreOrderReceiptAddress.setProvince(receiptAddress.getString("province"));
        aeStoreOrderReceiptAddress.setZip(receiptAddress.getString("zip"));
        aeStoreOrderReceiptAddress.setOrderId(aeStoreOrder.getOrderId());
        aeStoreOrderReceiptAddress.setOaid(orderDetails.getString("oaid"));
        //解密收货人信息
        aeStoreOrderReceiptAddress = tradeSellerOrderDecrypt(aeStoreOrderReceiptAddress, accessToken);
        AeStoreOrderReceiptAddress aeStoreOrderReceiptAddressSel = aeStoreOrderReceiptAddressMapper.selectOne(
                new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, aeStoreOrder.getOrderId())
        );
        if (aeStoreOrderReceiptAddressSel != null) {
            aeStoreOrderReceiptAddress.setId(aeStoreOrderReceiptAddressSel.getId());
        }

        //子订单列表
        List<AeStoreChildOrder> aeStoreChildOrderList = new ArrayList<>();
        //订单商品
        List<AeStoreOrderProduct> aeStoreOrderProductList = new ArrayList<>();

        if (!orderDetails.getJSONObject("child_order_list").getString("aeop_tp_child_order_dto").equals("{}")) {
            JSONArray childOrderList = JSONArray.parseArray(orderDetails.getJSONObject("child_order_list").getString("aeop_tp_child_order_dto"));
            for (int i = 0; i < childOrderList.size(); i++) {
                JSONObject childOrderJson = childOrderList.getJSONObject(i);
                AeStoreChildOrder childOrder = aeStoreChildOrderMapper.selectOne(
                        new LambdaQueryWrapper<AeStoreChildOrder>().eq(AeStoreChildOrder::getChildOrderId, childOrderJson.getString("child_order_id"))
                );
                AeStoreOrderProduct aeStoreOrderProduct = aeStoreOrderProductMapper.selectOne(
                        new LambdaQueryWrapper<AeStoreOrderProduct>()
                                .eq(AeStoreOrderProduct::getChildId, childOrderJson.getString("child_order_id"))
                                .eq(AeStoreOrderProduct::getSkuCode, childOrderJson.getString("sku_code"))
                                .orderByDesc(AeStoreOrderProduct::getUpdateTime)
                                .last("limit 1")
                );

                if (ObjectUtils.isEmpty(childOrder)) {
                    childOrder = new AeStoreChildOrder();
                    childOrder.setChildOrderId(childOrderJson.getString("child_order_id"));
                    childOrder.setOrderId(orderDetails.getLong("id"));
                }
                if (ObjectUtils.isEmpty(aeStoreOrderProduct)) {
                    aeStoreOrderProduct = new AeStoreOrderProduct();
                    aeStoreOrderProduct.setChildId(childOrderJson.getLong("child_order_id"));
                    aeStoreOrderProduct.setOrderId(orderDetails.getLong("id"));
                }

                //物流类型，买家选择的物流方式
                childOrder.setLogisticsType(childOrderJson.getString("logistics_type"));
                aeStoreOrderProduct.setLogisticsType(childOrderJson.getString("logistics_type"));
                //每个piece或lot对应多少个产品
                childOrder.setLotNum(childOrderJson.getLong("lot_num"));
                //子订单序号，用于子订单发货，即sub_trade_order_index
                childOrder.setOrderSortId(childOrderJson.getString("order_sort_id"));
                //订单状态：PLACE_ORDER_SUCCESS:等待买家付款; IN_CANCEL:买家申请取消; WAIT_SELLER_SEND_GOODS:等待您发货; SELLER_PART_SEND_GOODS:部分发货; WAIT_BUYER_ACCEPT_GOODS:等待买家收货; FUND_PROCESSING:买卖家达成一致，资金处理中； IN_ISSUE:含纠纷中的订单; IN_FROZEN:冻结中的订单; WAIT_SELLER_EXAMINE_MONEY:等待您确认金额; RISK_CONTROL:订单处于风控24小时中，从买家在线支付完成后开始，持续24小时。
                childOrder.setOrderStatus(childOrderJson.getString("order_status"));
                //商品扩展属性，skuid等
                childOrder.setProductAttributes(childOrderJson.getString("product_attributes"));
                //商品数量
                childOrder.setProductCount(childOrderJson.getLong("product_count"));
                aeStoreOrderProduct.setProductCount(childOrderJson.getLong("product_count"));
                //商品ID
                childOrder.setProductId(childOrderJson.getLong("product_id"));
                aeStoreOrderProduct.setProductId(childOrderJson.getLong("product_id"));
                //商品名称
                childOrder.setProductName(childOrderJson.getString("product_name"));
                aeStoreOrderProduct.setProductName(childOrderJson.getString("product_name"));
                //产品单位
                childOrder.setProductUnit(childOrderJson.getString("product_unit"));
                aeStoreOrderProduct.setProductUnit(childOrderJson.getString("product_unit"));
                //商品单价
                JSONObject productPriceJson = JSONObject.parseObject(childOrderJson.getString("product_price"));
                childOrder.setProductPrice(productPriceJson.getString("amount"));
                aeStoreOrderProduct.setProductAmount(productPriceJson.getString("amount"));
                childOrder.setProductCent(productPriceJson.getBigDecimal("cent"));
                aeStoreOrderProduct.setProductCent(productPriceJson.getBigDecimal("cent"));
                childOrder.setProductCentFactor(productPriceJson.getLong("cent_factor"));
                aeStoreOrderProduct.setProductCentFactor(productPriceJson.getLong("cent_factor"));
                childOrder.setProductCurrencyCode(productPriceJson.getString("currency_code"));
                aeStoreOrderProduct.setTotalProductCurrencyCode(productPriceJson.getString("currency_code"));

                //发货类型"SELLER_SEND_GOODS": 卖家发货; "WAREHOUSE_SEND_GOODS":仓库发货
                childOrder.setSendGoodsOperator(childOrderJson.getString("send_goods_operator"));
                aeStoreOrderProduct.setSendGoodsOperator(childOrderJson.getString("send_goods_operator"));
                //sku
                childOrder.setSkuCode(childOrderJson.getString("sku_code"));
                aeStoreOrderProduct.setSkuCode(childOrderJson.getString("sku_code"));
                //快照ID
                childOrder.setSnapshotId(childOrderJson.getString("snapshot_id"));
                //产品快照的图片路径
                childOrder.setSnapshotSmallPhotoPath(childOrderJson.getString("snapshot_small_photo_path"));
                //商品主图Url
                childOrder.setProductImgUrl(childOrderJson.getString("product_img_url"));
                aeStoreOrderProduct.setProductImgUrl(childOrderJson.getString("product_img_url"));
                //快照Url
                childOrder.setProductSnapUrl(childOrderJson.getString("product_snap_url"));
                aeStoreOrderProduct.setProductSnapUrl(childOrderJson.getString("product_snap_url"));
                //备货时间
                childOrder.setGoodsPrepareTime(childOrderJson.getLong("goods_prepare_time"));
                aeStoreOrderProduct.setGoodsPrepareTime(childOrderJson.getLong("goods_prepare_time"));
                //物流服务
                childOrder.setLogisticsServiceName(childOrderJson.getString("logistics_service_name"));
                aeStoreOrderProduct.setLogisticsServiceName(childOrderJson.getString("logistics_service_name"));
                //买家备注(子订单级别)
                childOrder.setBuyerMemo(childOrderJson.getString("buyer_memo"));
                //cainiaoInternationalWarehouse表示是菜鸟认证海外仓发货的，这类订单（子订单）将由菜鸟系统下发海外仓系统，进行订单履行，商家ERP需进行过滤此类型的订单（子订单）。其他情况为空
                childOrder.setLogisticsWarehouseType(childOrderJson.getString("logistics_warehouse_type"));
                //子订单中的各种标
                childOrder.setTags(childOrderJson.getString("tags"));
                aeStoreOrderProduct.setTags(childOrderJson.getString("tags"));
                //U_TAXED海外仓已税，跨境已税是I_TAXED
                childOrder.setAlreadyTaxed(childOrderJson.getString("already_taxed"));
                //[{"zh_CN":"存储子订单的拓展参数，是一个map 序列化成Json的，orderBusinessModel:SEMI_CHOICE_SELF"是半托管}]
                childOrder.setExtendMap(childOrderJson.getString("extend_map"));
                //联盟佣金比例
                childOrder.setAfflicateFeeRate(childOrderJson.getString("afflicate_fee_rate"));
                aeStoreOrderProduct.setAfflicateFeeRate(childOrderJson.getString("afflicate_fee_rate"));

                //子订单纠纷信息
                //纠纷状态 处理中 processing、 纠纷取消canceled_issue、纠纷完结,退款处理完成finish
                childOrder.setIssueStatus(childOrderJson.getString("issue_status"));
                aeStoreOrderProduct.setIssueStatus(childOrderJson.getString("issue_status"));
                if (!childOrderJson.getString("issue_status").equals("NO_ISSUE")) {
                    JSONObject childIssueInfoJson = JSONObject.parseObject(childOrderJson.getString("child_issue_info"));
                    //纠纷创建时间
                    childOrder.setIssueTime(childIssueInfoJson.getString("issue_time"));
                    //纠纷类型
                    childOrder.setIssueModel(childIssueInfoJson.getString("issue_model"));
                }
                childOrder.setEscrowFeeRate(childOrderJson.getString("escrow_fee_rate"));
                aeStoreOrderProduct.setEscrowFeeRate(childOrderJson.getString("escrow_fee_rate"));

                //冻结状态（NO_FROZEN:未冻结；IN_FROZEN:冻结中）
                childOrder.setFrozenStatus(childOrderJson.getString("frozen_status"));
                //资金状态(NOT_PAY：待支付；PAY_SUCCESS:支付成功)
                childOrder.setFundStatus(childOrderJson.getString("fund_status"));
                //订单ID
                childOrder.setId(childOrderJson.getLong("id"));
                //订单原始总金额
                JSONObject initOrderAmtJson = JSONObject.parseObject(childOrderJson.getString("product_price"));
                childOrder.setInitOrderCent(initOrderAmtJson.getBigDecimal("cent"));
                childOrder.setInitOrderAmount(initOrderAmtJson.getString("amount"));
                childOrder.setInitOrderCurrencyCode(initOrderAmtJson.getString("currency_code"));
                childOrder.setInitOrderCentFactor(initOrderAmtJson.getLong("cent_factor"));
                aeStoreChildOrderList.add(childOrder);
                aeStoreOrderProductList.add(aeStoreOrderProduct);
            }


        }

        // 插入数据
        aeStoreOrderMapper.insert(aeStoreOrder);
        aeStoreOrderProductMapper.insertBatch(aeStoreOrderProductList);
        aeStoreOrderReceiptAddressMapper.insert(aeStoreOrderReceiptAddress);
        aeStoreChildOrderMapper.insertBatch(aeStoreChildOrderList);

        // 组装新订单完整信息
        Map<String, Object> newOrderMap = new HashMap<>();
        newOrderMap.put("newOrder", aeStoreOrder);
        newOrderMap.put("newOrderProductList", aeStoreOrderProductList);
        newOrderMap.put("newOrderReceiptAddress", aeStoreOrderReceiptAddress);
        newOrderMap.put("newChildOrderList", aeStoreChildOrderList);
        newOrderMap.put("type", 0);
        // 分发单条新订单信息并进行业务处理
        rabbitTemplate.convertAndSend("pull-order-event-exchange",
                "pull.new.order.divide", JSONObject.toJSONString(newOrderMap));
        return newOrderMap;

//        return  returnErpOrderList(aeStoreOrder.getOrderId());
    }

    @Override
    public Map<String, Object> saveAeIncrementalOrderInfo(AeStoreOrder aeStoreOrder, JSONObject orderDetails, String accessToken) {
        //保存基本信息
        aeStoreOrder = saveAeStoreOrderByDetails(aeStoreOrder, orderDetails);
        //订单id
        Long orderId = aeStoreOrder.getOrderId();

        //AE_STORE_ORDER_RECEIPT_ADDRESS 收货人信息
        JSONObject receiptAddress = orderDetails.getJSONObject("receipt_address");
        AeStoreOrderReceiptAddress aeStoreOrderReceiptAddress = new AeStoreOrderReceiptAddress();
        aeStoreOrderReceiptAddress.setAddress(receiptAddress.getString("address"));
        aeStoreOrderReceiptAddress.setAddress2(receiptAddress.getString("address2"));
        aeStoreOrderReceiptAddress.setCity(receiptAddress.getString("city"));
        aeStoreOrderReceiptAddress.setContactPerson(receiptAddress.getString("contact_person"));
        aeStoreOrderReceiptAddress.setCountry(receiptAddress.getString("country"));
        aeStoreOrderReceiptAddress.setDetailAddress(receiptAddress.getString("detail_address"));
        aeStoreOrderReceiptAddress.setMobileNo(receiptAddress.getString("mobile_no"));
        aeStoreOrderReceiptAddress.setPhoneCountry(receiptAddress.getString("phone_country"));
        aeStoreOrderReceiptAddress.setProvince(receiptAddress.getString("province"));
        aeStoreOrderReceiptAddress.setZip(receiptAddress.getString("zip"));
        aeStoreOrderReceiptAddress.setOrderId(aeStoreOrder.getOrderId());
        aeStoreOrderReceiptAddress.setOaid(orderDetails.getString("oaid"));
        //解密收货人信息
        aeStoreOrderReceiptAddress = tradeSellerOrderDecrypt(aeStoreOrderReceiptAddress, accessToken);
        AeStoreOrderReceiptAddress aeStoreOrderReceiptAddressSel = aeStoreOrderReceiptAddressMapper.selectOne(
                new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, aeStoreOrder.getOrderId())
        );
        if (aeStoreOrderReceiptAddressSel != null) {
            aeStoreOrderReceiptAddress.setId(aeStoreOrderReceiptAddressSel.getId());
        }

        //子订单列表
        List<AeStoreChildOrder> aeStoreChildOrderList = new ArrayList<>();
        //订单商品
        List<AeStoreOrderProduct> aeStoreOrderProductList = new ArrayList<>();

        if (!orderDetails.getJSONObject("child_order_list").getString("aeop_tp_child_order_dto").equals("{}")) {
            JSONArray childOrderList = JSONArray.parseArray(orderDetails.getJSONObject("child_order_list").getString("aeop_tp_child_order_dto"));
            for (int i = 0; i < childOrderList.size(); i++) {
                JSONObject childOrderJson = childOrderList.getJSONObject(i);
                AeStoreChildOrder childOrder = aeStoreChildOrderMapper.selectOne(
                        new LambdaQueryWrapper<AeStoreChildOrder>().eq(AeStoreChildOrder::getChildOrderId, childOrderJson.getString("child_order_id"))
                );
                AeStoreOrderProduct aeStoreOrderProduct = aeStoreOrderProductMapper.selectOne(
                        new LambdaQueryWrapper<AeStoreOrderProduct>()
                                .eq(AeStoreOrderProduct::getChildId, childOrderJson.getString("child_order_id"))
                                .eq(AeStoreOrderProduct::getSkuCode, childOrderJson.getString("sku_code"))
                                .orderByDesc(AeStoreOrderProduct::getUpdateTime)
                                .last("limit 1")
                );

                if (ObjectUtils.isEmpty(childOrder)) {
                    childOrder = new AeStoreChildOrder();
                    childOrder.setChildOrderId(childOrderJson.getString("child_order_id"));
                    childOrder.setOrderId(orderDetails.getLong("id"));
                }
                if (ObjectUtils.isEmpty(aeStoreOrderProduct)) {
                    aeStoreOrderProduct = new AeStoreOrderProduct();
                    aeStoreOrderProduct.setChildId(childOrderJson.getLong("child_order_id"));
                    aeStoreOrderProduct.setOrderId(orderDetails.getLong("id"));
                }

                //物流类型，买家选择的物流方式
                childOrder.setLogisticsType(childOrderJson.getString("logistics_type"));
                aeStoreOrderProduct.setLogisticsType(childOrderJson.getString("logistics_type"));
                //每个piece或lot对应多少个产品
                childOrder.setLotNum(childOrderJson.getLong("lot_num"));
                //子订单序号，用于子订单发货，即sub_trade_order_index
                childOrder.setOrderSortId(childOrderJson.getString("order_sort_id"));
                //订单状态：PLACE_ORDER_SUCCESS:等待买家付款; IN_CANCEL:买家申请取消; WAIT_SELLER_SEND_GOODS:等待您发货; SELLER_PART_SEND_GOODS:部分发货; WAIT_BUYER_ACCEPT_GOODS:等待买家收货; FUND_PROCESSING:买卖家达成一致，资金处理中； IN_ISSUE:含纠纷中的订单; IN_FROZEN:冻结中的订单; WAIT_SELLER_EXAMINE_MONEY:等待您确认金额; RISK_CONTROL:订单处于风控24小时中，从买家在线支付完成后开始，持续24小时。
                childOrder.setOrderStatus(childOrderJson.getString("order_status"));
                //商品扩展属性，skuid等
                childOrder.setProductAttributes(childOrderJson.getString("product_attributes"));
                //商品数量
                childOrder.setProductCount(childOrderJson.getLong("product_count"));
                aeStoreOrderProduct.setProductCount(childOrderJson.getLong("product_count"));
                //商品ID
                childOrder.setProductId(childOrderJson.getLong("product_id"));
                aeStoreOrderProduct.setProductId(childOrderJson.getLong("product_id"));
                //商品名称
                childOrder.setProductName(childOrderJson.getString("product_name"));
                aeStoreOrderProduct.setProductName(childOrderJson.getString("product_name"));
                //产品单位
                childOrder.setProductUnit(childOrderJson.getString("product_unit"));
                aeStoreOrderProduct.setProductUnit(childOrderJson.getString("product_unit"));
                //商品单价
                JSONObject productPriceJson = JSONObject.parseObject(childOrderJson.getString("product_price"));
                childOrder.setProductPrice(productPriceJson.getString("amount"));
                aeStoreOrderProduct.setProductAmount(productPriceJson.getString("amount"));
                childOrder.setProductCent(productPriceJson.getBigDecimal("cent"));
                aeStoreOrderProduct.setProductCent(productPriceJson.getBigDecimal("cent"));
                childOrder.setProductCentFactor(productPriceJson.getLong("cent_factor"));
                aeStoreOrderProduct.setProductCentFactor(productPriceJson.getLong("cent_factor"));
                childOrder.setProductCurrencyCode(productPriceJson.getString("currency_code"));
                aeStoreOrderProduct.setTotalProductCurrencyCode(productPriceJson.getString("currency_code"));

                //发货类型"SELLER_SEND_GOODS": 卖家发货; "WAREHOUSE_SEND_GOODS":仓库发货
                childOrder.setSendGoodsOperator(childOrderJson.getString("send_goods_operator"));
                aeStoreOrderProduct.setSendGoodsOperator(childOrderJson.getString("send_goods_operator"));
                //sku
                childOrder.setSkuCode(childOrderJson.getString("sku_code"));
                aeStoreOrderProduct.setSkuCode(childOrderJson.getString("sku_code"));
                //快照ID
                childOrder.setSnapshotId(childOrderJson.getString("snapshot_id"));
                //产品快照的图片路径
                childOrder.setSnapshotSmallPhotoPath(childOrderJson.getString("snapshot_small_photo_path"));
                //商品主图Url
                childOrder.setProductImgUrl(childOrderJson.getString("product_img_url"));
                aeStoreOrderProduct.setProductImgUrl(childOrderJson.getString("product_img_url"));
                //快照Url
                childOrder.setProductSnapUrl(childOrderJson.getString("product_snap_url"));
                aeStoreOrderProduct.setProductSnapUrl(childOrderJson.getString("product_snap_url"));
                //备货时间
                childOrder.setGoodsPrepareTime(childOrderJson.getLong("goods_prepare_time"));
                aeStoreOrderProduct.setGoodsPrepareTime(childOrderJson.getLong("goods_prepare_time"));
                //物流服务
                childOrder.setLogisticsServiceName(childOrderJson.getString("logistics_service_name"));
                aeStoreOrderProduct.setLogisticsServiceName(childOrderJson.getString("logistics_service_name"));
                //买家备注(子订单级别)
                childOrder.setBuyerMemo(childOrderJson.getString("buyer_memo"));
                //cainiaoInternationalWarehouse表示是菜鸟认证海外仓发货的，这类订单（子订单）将由菜鸟系统下发海外仓系统，进行订单履行，商家ERP需进行过滤此类型的订单（子订单）。其他情况为空
                childOrder.setLogisticsWarehouseType(childOrderJson.getString("logistics_warehouse_type"));
                //子订单中的各种标
                childOrder.setTags(childOrderJson.getString("tags"));
                aeStoreOrderProduct.setTags(childOrderJson.getString("tags"));
                //U_TAXED海外仓已税，跨境已税是I_TAXED
                childOrder.setAlreadyTaxed(childOrderJson.getString("already_taxed"));
                //[{"zh_CN":"存储子订单的拓展参数，是一个map 序列化成Json的，orderBusinessModel:SEMI_CHOICE_SELF"是半托管}]
                childOrder.setExtendMap(childOrderJson.getString("extend_map"));
                //联盟佣金比例
                childOrder.setAfflicateFeeRate(childOrderJson.getString("afflicate_fee_rate"));
                aeStoreOrderProduct.setAfflicateFeeRate(childOrderJson.getString("afflicate_fee_rate"));

                //子订单纠纷信息
                //纠纷状态 处理中 processing、 纠纷取消canceled_issue、纠纷完结,退款处理完成finish
                childOrder.setIssueStatus(childOrderJson.getString("issue_status"));
                aeStoreOrderProduct.setIssueStatus(childOrderJson.getString("issue_status"));
                if (!childOrderJson.getString("issue_status").equals("NO_ISSUE")) {
                    JSONObject childIssueInfoJson = JSONObject.parseObject(childOrderJson.getString("child_issue_info"));
                    //纠纷创建时间
                    childOrder.setIssueTime(childIssueInfoJson.getString("issue_time"));
                    //纠纷类型
                    childOrder.setIssueModel(childIssueInfoJson.getString("issue_model"));
                }
                childOrder.setEscrowFeeRate(childOrderJson.getString("escrow_fee_rate"));
                aeStoreOrderProduct.setEscrowFeeRate(childOrderJson.getString("escrow_fee_rate"));

                //冻结状态（NO_FROZEN:未冻结；IN_FROZEN:冻结中）
                childOrder.setFrozenStatus(childOrderJson.getString("frozen_status"));
                //资金状态(NOT_PAY：待支付；PAY_SUCCESS:支付成功)
                childOrder.setFundStatus(childOrderJson.getString("fund_status"));
                //订单ID
                childOrder.setId(childOrderJson.getLong("id"));
                //订单原始总金额
                JSONObject initOrderAmtJson = JSONObject.parseObject(childOrderJson.getString("product_price"));
                childOrder.setInitOrderCent(initOrderAmtJson.getBigDecimal("cent"));
                childOrder.setInitOrderAmount(initOrderAmtJson.getString("amount"));
                childOrder.setInitOrderCurrencyCode(initOrderAmtJson.getString("currency_code"));
                childOrder.setInitOrderCentFactor(initOrderAmtJson.getLong("cent_factor"));
                aeStoreChildOrderList.add(childOrder);
                aeStoreOrderProductList.add(aeStoreOrderProduct);
            }


        }

        // 更新数据
        AeStoreOrder orderSel = aeStoreOrderMapper.selectByOrderId(aeStoreOrder.getOrderId());
        if (ObjectUtils.isNotNull(orderSel)) {
            aeStoreOrder.setId(orderSel.getId());
            aeStoreOrderMapper.updateById(orderSel);
        }

        aeStoreOrderReceiptAddressMapper.updateById(aeStoreOrderReceiptAddress);

        //删除原有订单商品表的品的重新插入
        aeStoreOrderProductMapper.delete(
                new LambdaQueryWrapper<AeStoreOrderProduct>().eq(AeStoreOrderProduct::getOrderId, orderId)
        );
        aeStoreOrderProductMapper.insertBatch(aeStoreOrderProductList);

        //删除原有的子订单的品重新插入
        aeStoreChildOrderMapper.delete(
                new LambdaQueryWrapper<AeStoreChildOrder>().eq(AeStoreChildOrder::getOrderId, orderId)
        );
        aeStoreChildOrderMapper.insertBatch(aeStoreChildOrderList);

        // 组装新订单完整信息
        Map<String, Object> newOrderMap = new HashMap<>();
        newOrderMap.put("newOrder", aeStoreOrder);
        newOrderMap.put("newOrderProductList", aeStoreOrderProductList);
        newOrderMap.put("newOrderReceiptAddress", aeStoreOrderReceiptAddress);
        newOrderMap.put("newChildOrderList", aeStoreChildOrderList);
        newOrderMap.put("type", 1);
        // 分发单条新订单信息并进行业务处理
        rabbitTemplate.convertAndSend("pull-order-event-exchange",
                "pull.incremental.order.divide", JSONObject.toJSONString(newOrderMap));
        return newOrderMap;

//        return  returnErpOrderList(aeStoreOrder.getOrderId());
    }


    /**
     * @param storeUserName
     * @param createDateStart
     * @return
     * @Description: 根据店铺cn码和订单时间，查询店铺列表
     * @Author: j.zh
     * @Date: 2024/5/9
     * @Version: 4.0.0
     **/
    @Override
    public List<AeStoreOrder> getListByStoreUserName(String storeUserName, String createDateStart, String createDateEnd) {
        return aeStoreOrderMapper.selectList(new LambdaQueryWrapper<AeStoreOrder>().eq(AeStoreOrder::getSellerLoginId, storeUserName)
                .ge(createDateStart != null, AeStoreOrder::getGmtCreate, createDateStart)
                .le(createDateEnd != null, AeStoreOrder::getGmtCreate, createDateEnd));
    }

    /**
     * 填补AeStoreOrder
     *
     * @param aeStoreOrder
     * @param orderDetails
     * @return
     */
    private AeStoreOrder saveAeStoreOrderByDetails(AeStoreOrder aeStoreOrder, JSONObject orderDetails) {
        //填补信息
//        aeStoreOrder.setSellerOperatorAliidloginid(orderDetails.getString("seller_operator_aliidloginid"));
        aeStoreOrder.setSettlementCurrency(orderDetails.getString("settlement_currency"));
        aeStoreOrder.setCod(orderDetails.getString("cod"));
        aeStoreOrder.setCancelRequestReason(orderDetails.getString("cancel_request_reason"));
        // 新订单金额 含税价订单，不含税金
        JSONObject newOrderAmount = orderDetails.getJSONObject("new_order_amount");
        aeStoreOrder.setNewOrderAmount(newOrderAmount.getString("amount"));
        aeStoreOrder.setNewOrderCurrencyCode(newOrderAmount.getString("currency_code"));
        //  新订单金额
        JSONObject sellerOrderAmount = orderDetails.getJSONObject("seller_order_amount");
        aeStoreOrder.setSellerOrderAmount(sellerOrderAmount.getString("amount"));
        aeStoreOrder.setSellerOrderCurrencyCode(sellerOrderAmount.getString("currency_code"));

        //买家信息
        JSONObject buyerInfo = orderDetails.getJSONObject("buyer_info");
        aeStoreOrder.setBuyerCountry(buyerInfo.getString("country"));
        aeStoreOrder.setBuyerLastName(buyerInfo.getString("first_name"));
        aeStoreOrder.setBuyerFirstName(buyerInfo.getString("last_name"));

        //订单最后更新时间
        aeStoreOrder.setGmtTradeEnd(orderDetails.getString("gmt_trade_end"));
        //订单创建时间
        aeStoreOrder.setGmtCreate(orderDetails.getString("gmt_create"));
        //订单支付成功时间
        String paySuccess = orderDetails.getString("gmt_pay_success");
        if (paySuccess != null) {
            aeStoreOrder.setGmtPayTime(paySuccess);
        }
        //备注
        aeStoreOrder.setMemo(orderDetails.getString("memo"));
        //结束原因
        aeStoreOrder.setOrderEndReason(orderDetails.getString("order_end_reason"));
        //买家支付金额(结算币种)
//        JSONObject payAmount = orderDetails.getJSONObject("pay_amount_by_settlement_cur");
//        aeStoreOrder.setPayAmount(payAmount.getString("amount"));
        //买家支付金额(结算币种)
//        aeStoreOrder.setPayCurrencyCode(payAmount.getString("currency_code"));
        aeStoreOrder.setPayAmount(orderDetails.getString("pay_amount_by_settlement_cur"));
        //付款方式 （migs信用卡支付走人民币渠道； migs102MasterCard支付并且走人民币渠道； migs101Visa支付并且走人民币渠道； pp101 PayPal； mb MoneyBooker渠道； tt101 Bank Transfer支付； wu101 West Union支付； wp101 Visa走美金渠道的支付； wp102 Mastercard 走美金渠道的支付； qw101 QIWI支付； cybs101 Visa走CYBS渠道的支付； cybs102 Mastercard 走CYBS渠道的支付； wm101 WebMoney支付； ebanx101 巴西Beloto支付 ；）
        aeStoreOrder.setPaymentType(orderDetails.getString("payment_type"));
        //订单金额
        JSONObject orderAmount = orderDetails.getJSONObject("order_amount");
        aeStoreOrder.setOrderAmount(orderAmount.getString("amount"));
        aeStoreOrder.setOrderCent(orderAmount.getBigDecimal("cent"));
        aeStoreOrder.setOrderCentFactor(orderAmount.getLong("cent_factor"));
        //货币描述
        JSONObject orderCurrency = orderAmount.getJSONObject("currency");
        aeStoreOrder.setOrderCurrencyDescriptionId(
                returnCurrencyDescriptionId(
                        orderAmount.getString("currency_code"),
                        orderCurrency.getBigDecimal("default_fraction_digits"),
                        orderCurrency.getString("display_name"),
                        orderCurrency.getLong("numeric_code"),
                        orderCurrency.getString("symbol")
                )
        );

        //订单到期时间
        aeStoreOrder.setLeftEndGoodTime(orderDetails.getString("over_time_left"));

        aeStoreOrder.setSellerOperatorLoginId(orderDetails.getString("seller_operator_login_id"));
        aeStoreOrder.setSellerSignerFullname(orderDetails.getString("seller_signer_fullname"));
        aeStoreOrder.setOrderStatus(orderDetails.getString("order_status"));


        return aeStoreOrder;
    }

    /**
     * 返回CurrencyDescriptionId
     *
     * @param currencyCode
     * @param defaultFractionDigits
     * @param displayName
     * @param numericCode
     * @param symbol
     * @return
     */
    private Long returnCurrencyDescriptionId(String currencyCode,
                                             BigDecimal defaultFractionDigits,
                                             String displayName,
                                             Long numericCode,
                                             String symbol) {
        Long id = aeCurrencyDescriptionMapper.returnCurrencyDescriptionId(currencyCode);
        //若id为空，则新插入
        if (id == null) {
            AeCurrencyDescription aeCurrencyDescription = new AeCurrencyDescription();
            aeCurrencyDescription.setCurrencyCode(currencyCode);
            aeCurrencyDescription.setSymbol(symbol);
            aeCurrencyDescription.setNumericCode(numericCode);
            aeCurrencyDescription.setDisplayName(displayName);
            aeCurrencyDescription.setDefaultFractionDigits(defaultFractionDigits);
            aeCurrencyDescriptionMapper.insert(aeCurrencyDescription);
            id = aeCurrencyDescriptionMapper.returnCurrencyDescriptionId(currencyCode);
        }
        return id;
    }
}
